// pages/theatre/theatre.js
const app = getApp().globalData;
const wxAPI = require("../../libs/wxAPI")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    city: "未选择",
    keyWords: "",
    cinemaList: [],
    limit: 20,
    // 分页页码，未实现，api真机限制
    page_index: 1
  },
  // 搜索影院
  searchCinema() {
    let that = this;
    that.data.cinemaList=[];
    console.log(that.data.keyWords);
    // 拼接检索数据索引
    let str=app.cityName+that.data.keyWords;
    // console.log(str);
    // 执行数据检索
    that.loadCinema(str);
  },
  // 打开地图(根据经纬度)
  tapCinema(e) {
    let i = e.currentTarget.dataset.index;
    let cinema = this.data.cinemaList[i];
    wx.openLocation({
      title: cinema.title,
      address: cinema.address,
      latitude: cinema.location.lat,
      longitude: cinema.location.lng,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  /**
   * function：随着定位查找周围电影院
   * @param {string} keyWords - 市名称 
   */
  loadCinema(keyWords) {
    let that = this;
    // console.log(that.data.keyWords);
    app.qqmapsdk.search({
      keyword: keyWords + "影院",
      page_size: this.data.limit,
      // page_index:this.data.page_index,
      success: (res => {
        console.log(res.data);
        let obj = [];
        for (let item of res.data) {
          // 对数据进行过滤，处理
          obj.push({
            title: item.title,
            address: item.address,
            _distance: (item._distance / 1000).toFixed(2) + "km",
            tel: (item.tel.indexOf(';') == -1) ? item.tel : item.tel.substring(0, item.tel.indexOf(";")),
            location: item.location
          })
        }
        // console.log(obj);
        // 将处理好的数据连接到数组后面
        that.setData({
          cinemaList: that.data.cinemaList.concat(obj)
        })
      }),
      fail: (err) => {
        console.log("-----");
        console.error(err);
      }
    })

  },
  onShow() {
    let that = this;
    // that.data.page_index=1;
    that.data.cinemaList = [];
    that.setData({
      city: getApp().globalData.cityName,
      keyWords: ""
    })
    that.loadCinema(app.cityName);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    wxAPI.toast('亲！到底了', "error");
    // let that = this;
    // console.log(that.data.page_index);
    // if( that.data.page_index>4){
    //   wxAPI.toast('亲！到底了', "error")
    // }else{
    //   that.data.page_index++;
    //   that.loadCinema(app.cityName)
    // }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})